<template>
  <div>
    exportJson2Excel
    <button @click="exportJson2Excel1">导出</button>
    <button @click="importJson">导入</button>
    <input type="file" ref="file" @change="getFile" />
  </div>
</template>

<script>
import FileSaver from "file-saver";
import XLSX from "xlsx";
function exportJson2Excel(data, fileName, sheetName) {
  const sheet = XLSX.utils.json_to_sheet(data);
  FileSaver.saveAs(
    new Blob([sheet2Blob(sheet, sheetName)], {
      type: "application/octet-stream;charset=utf-8",
    }),
    fileName
  );
}

function sheet2Blob(sheet, sheetName) {
  sheetName = sheetName || "sheet1";
  const workbook = {
    SheetNames: [sheetName],
    Sheets: {},
  };
  workbook.Sheets[sheetName] = sheet;
  // 生成excel的配置项
  const wopts = {
    bookType: "xlsx", // 要生成的文件类型
    bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
    type: "binary",
  };
  const wbout = XLSX.write(workbook, wopts);
  const blob = new Blob([string2ArrayBuffer(wbout)], {
    type: "application/octet-stream",
  });
  return blob;
}

// 字符串转ArrayBuffer
function string2ArrayBuffer(s) {
  console.log(s);
  const buf = new ArrayBuffer(s.length);
  const view = new Uint8Array(buf);
  for (let i = 0; i < s.length; ++i) {
    view[i] = s.charCodeAt(i) & 0xff;
  }
  return buf;
}
export default {
  data() {
    return {
      list: [
        {
          //测试数据

          货号: "goodsNo",
          商品条码: "skuNo2",
          商品品牌: "brand1",
          "净容积(cm^3)": "netVolume3",
        },
        {
          货号: "goodsNo",
          商品条码: "skuNo",
          商品品牌: "brand",
          "净容积(cm^3)": "netVolume",
        },
        {
          货号: "goodsNo",
          商品条码: "skuNo",
          商品品牌: "brand",
          "净容积(cm^3)": "netVolume",
        },
      ],
    };
  },
  methods: {
    exportJson2Excel1() {
      exportJson2Excel(this.list, "1.xlsx");
    },
    importJson() {
      this.$refs.file.click();
    },
    getFile(e) {
      /*
        FileReader共有4种读取方法：
        1.readAsArrayBuffer(file)：将文件读取为ArrayBuffer。
        2.readAsBinaryString(file)：将文件读取为二进制字符串
        3.readAsDataURL(file)：将文件读取为Data URL
        4.readAsText(file, [encoding])：将文件读取为文本，encoding缺省值为'UTF-8'
      */
      console.log(e);
      let base = new FileReader();
      // base.readAsDataURL(e.target.files[0]); { type: "base64" }
      base.readAsBinaryString(e.target.files[0]); // { type: "binary" }
      console.log(e.target.result);
      // String.fromCharCode(97);
      // ("a");
      base.onload = async function (e) {
        console.log(e.target.result);
        let context = XLSX.read(e.target.result, { type: "binary" });
        console.log(context);
        let excel = XLSX.utils.sheet_to_json(
          context.Sheets[context.SheetNames[0]],
          {
            /** Default value for null/undefined values */
            defval: "", //给defval赋值为空的字符串
          }
        );
        console.log(excel);
        exportJson2Excel(excel, "2.xlsx");
      };
    },
  },
};
</script>

<style>
</style>